<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\AuthAssignment;
use common\models\AuthItem;
use common\models\AuthItemChild;

class RoleForm extends Model
{
	public $auth;
	public $rolename;

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			[['rolename', 'auth'], 'required'],
		];
	}

	public function update()
	{
		$admin = AuthItem::find()->where(['type' => 1, 'name' => $this->rolename])->one();
		if ($admin) {
			$role = $admin;
			AuthItemChild::deleteAll(['parent' => $admin->name]);
			$rolename = $admin->name;
		} else {
			$rolename = uniqid() . '_admin';
			$role = new AuthItem;
			$role->type = 1;
			$role->name = $rolename;
			$role->description = $this->rolename;
			$role->data = "admin";
			$role->save(false);
		}

		foreach ($this->auth as $val) {
			$auth_item_child = new AuthItemChild;
			$auth_item_child->parent = $rolename;
			$auth_item_child->child = $val;
			$auth_item_child->save(false);
		}

		return true;
	}

}
